package com.huawei.esdk.uc.sametime.toolbar.actions;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import com.huawei.esdk.uc.sametime.util.GlobalConfiguration;
import com.huawei.esdk.uc.sametime.widgets.CallMemuUtil;
import com.ibm.collaboration.realtime.imhub.actions.BuddyListAction;
import com.ibm.collaboration.realtime.people.PeopleUtil;
import com.ibm.collaboration.realtime.people.Person;

/**
 * Voice Call Action contributed to the main window (buddy list).
 */

public class EsdkVoiceCallBuddyListDropDownAction extends BuddyListAction
{
    private CallMemuUtil menuCreator;

    public EsdkVoiceCallBuddyListDropDownAction()
    {
        super(null);
        menuCreator = new CallMemuUtil(false, false);
        setMenuCreator(menuCreator);
    }

    public void selectionChanged(SelectionChangedEvent event)
    {
        super.selectionChanged(event);
    }

    public void run()
    {
        Rectangle rect = getToolItemBounds();
        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                .getShell();

        Menu menu = menuCreator.getMenu(shell);
        if (rect != null)
        {
            menu.setLocation(rect.x, rect.y + rect.height);
        }
        menu.setVisible(true);
    }

    public boolean isEnabled()
    {
        // 这里判断插件是否登录UC
        boolean isUCLogin = GlobalConfiguration.getInstance().isUCLogin();
        // 这里判断插件是否登录sametime
        boolean isSametimeLogin = GlobalConfiguration.getInstance()
                .isSamtimeLogin();
//        boolean isInCall = (CallStatus.end != UCCallService.getCallStatus());

        // 只有同时登录了uc和sametime,才能使用工具栏上的功能
        if (isSametimeLogin && isUCLogin/* && !isInCall*/)
        {
            return isSelectPerson();
        }

        return false;
    }

    private boolean isSelectPerson()
    {
        IStructuredSelection sel = (IStructuredSelection) getCurrentSelection();
        if (null != sel && sel.size() == 1)
        {
            Object element = sel.getFirstElement();
            if (element instanceof Person)
            {
                if (!PeopleUtil.isMe(getSelectedPerson()))
                {
                    menuCreator.setSelectionPerson(getSelectedPerson());
                    return true;
                }
            }
        }
        return false;
    }

    private Person getSelectedPerson()
    {
        Person person = null;
        IStructuredSelection sel = (IStructuredSelection) getCurrentSelection();
        Object element = sel.getFirstElement();
        if (element instanceof Person)
        {
            person = (Person) element;
        }
        return person;
    }

}
